# -*- coding: utf-8 -*-
import base64
import hashlib

from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.PublicKey import RSA
#from common.log import logger
from logging import log

class RSASign:
    def __init__(self, rsa_pk, pk, pk_type=1):
        """
        :param rsa_pk: RSA私钥
        :param pk: 游戏key或平台代码
        :param pk_type: key类别，1代表是业务游戏key，0代表是总台plmId
        """
        self.rsa_pk = rsa_pk
        self.game_pk = pk
        self.game_pk_type = pk_type

    def _md5_str(self, dict_data):
        """
        计算请求参数的md5
        :param dict_data: 请求参数：dict
        :return: sign_md5: str
        """
        if not isinstance(dict_data, dict):
            return

        keys = sorted(dict_data.keys())

        pk = self.game_pk

        # 总台key处理
        if not self.game_pk_type:
            m5_plm = hashlib.md5(self.game_pk.encode())
            pk = m5_plm.hexdigest()
            logger.info('plm code md5: ' + pk)

        sign_params = ''
        for k in keys:
            if dict_data[k] != '' and dict_data[k] is not None and k != 'sign' and '@' != str(dict_data[k])[0]:
                sign_params += k + '=' + str(dict_data[k]) + '&'
        sign_params += 'key=' + pk

        logger.info('sign_params:' + sign_params)

        m = hashlib.md5(sign_params.encode())

        sign_md5 = m.hexdigest()
        # 总台的sign原始串要转大写
        if not self.game_pk_type:
            sign_md5 = sign_md5.upper()

        logger.info('sign md5:' + sign_md5)
        return sign_md5

    def _rsa_sign(self, text):
        """
        rsa签名
        :param text: 待签名的文本串
        :return: signature签名串
        """
        pk_kb = base64.b64decode(self.rsa_pk)
        pk = RSA.import_key(pk_kb)
        signer = Signature_pkcs1_v1_5.new(pk)

        digest = SHA256.new()
        digest.update(text.encode())

        sign = signer.sign(digest)
        signature = base64.b64encode(sign)

        logger.info(signature.decode())
        print(signature.decode)
        return signature.decode()


    def sign(self, dict_data):
        """
        返回签名后的数据
        :param dict_data: dict
        """
        dest_data = dict_data
        text = self._md5_str(dict_data)
        dest_data["sign"] = self._rsa_sign(text)
        print(dest_data)
        return dest_data

if __name__ == '__main__':
    Private = 'M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